//
//  ALPSearchViewController.m
//  AlpFM
//
//  Created by KING on 16/1/26.
//  Copyright © 2016年 Alp. All rights reserved.
//

#import "ALPSearchViewController.h"
#import <AFNetworking.h>
#import "ALPSearchModel.h"
#import "ALPListerModel.h"
#import "ALPListenAlbumTableViewCell.h"
#import "ALPListenDetailTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "ALPPlayViewController.h"
#import "ALPSingleModel.h"
#import "ALPEditorPlayVC.h"
#define COLOR_SELECTED [UIColor colorWithRed:0.98 green:0.35 blue:0.16 alpha:1]

@interface ALPSearchViewController ()
<
UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating
>

@property (nonatomic,retain) UISearchController *searchController;
@property (nonatomic,retain) UITableView *myTableView;
@property (nonatomic,retain) UITableView *searchResultTableView;

@property (nonatomic,retain) NSMutableArray *myArray;
@property (nonatomic, retain) NSMutableArray *albumArray;
@property (nonatomic ,retain) NSMutableArray *listArray;

@property (nonatomic, retain) UILabel *myLabel;

@end

@implementation ALPSearchViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.searchResultTableView reloadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //tableView
    self.navigationItem.title = @"搜索听";
    
    [self createTableView];
    //创建搜索
    [self createSearchBar];
    
    //左按钮
//    UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn_back_n@2x.png"]];
//    imgView.frame = CGRectMake(0, 0, 20, 30);
//    imgView.userInteractionEnabled = YES;
//    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rightBarButtonAction:)];
//    [imgView addGestureRecognizer:tap];
//    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:imgView];
//    self.navigationItem.leftBarButtonItem.tintColor = COLOR_SELECTED;
    
    self.tabBarController.tabBar.hidden = YES;
}

//#pragma mark - 左按钮的返回方法
//- (void)rightBarButtonAction:(UIBarButtonItem *)btn{
//    NSLog(@"POP");
//    [self.navigationController popViewControllerAnimated:YES];
//    
//}

#pragma mark - 创建收索
- (void)createSearchBar{
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //设置页面背景阴影效果(发暗)
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //点击搜索时隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.placeholder = @"搜索声音、专辑、人";
//    self.searchController.searchBar.tintColor = COLOR_SELECTED;
    self.searchController.searchBar.delegate = self;
    self.myTableView.tableHeaderView = self.searchController.searchBar;
    
//    self.navigationItem.titleView = self.searchController.searchBar;
    
}

#pragma mark - 创建tableView
-(void)createTableView{
    
    //候选tableView
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.myTableView];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"searchCell"];
    self.myTableView.bounces = NO;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //收索结果的tableView
    self.searchResultTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-100) style:UITableViewStylePlain];
//    self.searchResultTableView.backgroundColor = COLOR_BG;
    [self.view addSubview:self.searchResultTableView];

    self.searchResultTableView.dataSource = self;
    self.searchResultTableView.delegate = self;
    self.searchResultTableView.bounces = NO;
    self.searchResultTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.searchResultTableView registerClass:[ALPListenDetailTableViewCell class] forCellReuseIdentifier:@"searchDetialCell"];
    [self.searchResultTableView registerClass:[ALPListenAlbumTableViewCell class] forCellReuseIdentifier:@"searchAlbumCell"];
    
    //你想要的,这里都有
    self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(375/2, 667/2, 375/2, 667/3)];
//    self.myLabel.backgroundColor = CLEAR;
    self.myLabel.text = @"你想要的,这里都有";
    self.myLabel.textAlignment = NSTextAlignmentCenter;
    self.myLabel.textColor = [UIColor lightGrayColor];
    self.myLabel.center = CGPointMake(375/2, 667/3);
    [self.myTableView addSubview:self.myLabel];
    
    [self.view bringSubviewToFront:self.myTableView];
    
}

#pragma mark - 协议方法 组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == self.myTableView) {
        return 1;
    } else {
        return 2;
    }
}

#pragma mark - 协议方法 行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.myTableView) {
        return self.myArray.count;
    } else {
        return self.albumArray.count;
    }
}

#pragma mark - 协议方法 高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.myTableView) {
        return self.view.frame.size.height*0.06;
    } else {
        return self.view.frame.size.width*0.267;
    }
}
#pragma mark - 协议方法 cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ALPListenAlbumTableViewCell *albumCell = [tableView dequeueReusableCellWithIdentifier:@"searchAlbumCell"];
    ALPListenDetailTableViewCell *trackCell = [tableView dequeueReusableCellWithIdentifier:@"searchDetialCell"];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    
    //候选cell
    if (tableView == self.myTableView) {
        //高亮匹配
        NSRange range = NSMakeRange(0, 0);
        ALPSearchModel *model = [self.myArray objectAtIndex:indexPath.row];
        NSArray *strArray = [model.highlightKeyword componentsSeparatedByString:@"</em>"];
        if (strArray.count>1) {
            NSInteger length = ((NSString *)[strArray objectAtIndex:0]).length;
            range =  NSMakeRange(0, length-4);
        } else {
            range = NSMakeRange(0, 0);
        }
        
        NSMutableAttributedString *stringM = [[NSMutableAttributedString alloc] initWithString:model.keyword];
        [stringM addAttribute:NSForegroundColorAttributeName value:COLOR_SELECTED range:range];
        cell.textLabel.attributedText = stringM;
        cell.textLabel.font = [UIFont systemFontOfSize:0.039*375];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.imgPath] placeholderImage:[UIImage imageNamed:@"girledg"]];
        return cell;
        
        //专辑cell
    } else  if (tableView == self.searchResultTableView && indexPath.section == 0){
        
        ALPAlbumModel *model = [self.albumArray objectAtIndex:indexPath.row];
        albumCell.model = model;
        return albumCell;
        //歌曲cell
    } else {
        
        ALPListerModel *model = [self.listArray objectAtIndex:indexPath.row];
        trackCell.model = model;
        return trackCell;
        
    }
}

#pragma mark - 协议方法 头
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (tableView == self.searchResultTableView&&section == 0) {
        return @"专辑";
    } else if (tableView == self.searchResultTableView&&section == 1) {
        return @"声音";
    }
    return nil;
}

#pragma mark - 请求候选数据
- (void)getData:(NSString *)searchString{
    self.myArray = [NSMutableArray array];
    
    NSString *string = [NSString stringWithFormat:@"http://search.ximalaya.com/suggest?device=iphone&kw=%@", searchString];
//        NSLog(@"%@", string);
    //中文解码
    NSString *urlEncode = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    
    [session GET:urlEncode parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
//        NSLog(@"成功");
        NSMutableArray *albumArray = [responseObject objectForKey:@"albumResultList"];
        for (NSMutableDictionary *albumDic in albumArray) {
            ALPSearchModel *model = [[ALPSearchModel alloc] init];
            [model setValuesForKeysWithDictionary:albumDic];
//            ALPSearchModel *model = [ALPSearchModel modelWithDictionary:albumDic];
            [self.myArray addObject:model];
        }
        
        NSMutableArray *queryArray = [responseObject objectForKey:@"queryResultList"];
        for (NSMutableDictionary *queryDic in queryArray) {
            ALPSearchModel *model = [[ALPSearchModel alloc] init];
            [model setValuesForKeysWithDictionary:queryDic];
            [self.myArray addObject:model];
        }
        self.myLabel.alpha = 0;
        [self.myTableView reloadData];
//        NSLog(@"%ld",self.myArray.count);
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@"失败");
        
    }];

    }

#pragma mark - 请求选中后搜索的数据
- (void)getMoreData:(NSString *)cellString{
    self.albumArray = [NSMutableArray array];
    self.listArray = [NSMutableArray array];
//    NSLog(@"%@",cellString);
    NSString *str = [NSString stringWithFormat:@"http://search.ximalaya.com/front/v1?device=iphone&core=all&kw=%@&page=1&rows=3&spellchecker=true",cellString];
//        NSLog(@"xhf:%@",str);
    NSString *urlEncode = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
    [session GET:urlEncode parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
//        NSLog(@"成功");
        //专辑数据
       NSMutableArray *albumArray = [[responseObject objectForKey:@"album"] objectForKey:@"docs"];
       for (NSMutableDictionary *dic in albumArray) {
            ALPAlbumModel *model = [[ALPAlbumModel alloc] init];
           [model setValuesForKeysWithDictionary:dic];
            [self.albumArray addObject:model];
        }
        
        //        //歌曲数据
        NSMutableArray *trackArray = [[responseObject objectForKey:@"track"] objectForKey:@"docs"];
        for (NSMutableDictionary *dic in trackArray) {
            ALPListerModel *model = [[ALPListerModel alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
            [self.listArray addObject:model];
        }
                
        self.myLabel.alpha = 0;
        [self.searchResultTableView reloadData];
//        NSLog(@"%ld",self.myArray.count);
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@"失败");
        
    }];


}

#pragma mark - 点击取消按钮会触发的方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

#pragma mark - 输入框更新的时候就会触发
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    //把候选的tableView带到前面来
    [self.view bringSubviewToFront:self.myTableView];
    NSString *searchString = self.searchController.searchBar.text;
    
    //如果是空就无动作
    if ([searchString isEqualToString:@""]) {
        
    } else {
        //如果不是空就请求候选数据
        [self getData:searchString];
    }
    
   
}

#pragma mark - 选中执行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //候选cell点击
    if (tableView == self.myTableView) {
        ALPSearchModel *model = [self.myArray objectAtIndex:indexPath.row];
        //获取选中后的数据
//        NSLog(@"%@",model.keyword);
        [self getMoreData:model.keyword];
        //让输入框变成点中得文字
        self.searchController.searchBar.text = model.keyword;
        //将结果的tableView提前
        [self.view bringSubviewToFront:self.searchResultTableView];
        
    } else if (tableView == self.searchResultTableView&&indexPath.section == 0){
        //专辑区点击进入歌曲列表
        
        ALPAlbumModel *model = [self.albumArray objectAtIndex:indexPath.row];
        ALPEditorPlayVC *vc = [[ALPEditorPlayVC alloc] init];
        vc.idid = model.trackID.intValue;
        [self presentViewController:vc animated:YES completion:^{
            
            
        }];
//        HFMusicListViewController *vc = [[HFMusicListViewController alloc] init];
//        vc.pageID = model.trackID;
//        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
//        NSLog(@"ddddd");
        //歌曲区点击直接播放
        ALPPlayViewController *player = [ALPPlayViewController sharePlayerViewController];
        ALPListerModel *model = [self.listArray objectAtIndex:indexPath.row];
        player.song_ID = model.trackID.intValue;      //歌曲的ID
        player.indexRow = indexPath.row;     //点击的歌曲的下标
        NSString *str = [NSString stringWithFormat:@"%d",model.trackID.intValue];
        [[NSUserDefaults standardUserDefaults] setObject:str forKey:@"str"];
//        ***************** 数组转换 ****************
        NSMutableArray *array = [NSMutableArray array];
        for (ALPListerModel *lisionModel in self.listArray) {
            ALPSingleModel *listModel = [[ALPSingleModel alloc] init];
//            NSLog(@"AAA%@", lisionModel.trackID);
            listModel.trackId = [NSString stringWithFormat:@"%@", lisionModel.trackID];
            listModel.title = lisionModel.title;
            listModel.playtimes = lisionModel.playsCounts;
            listModel.comments = lisionModel.commentsCounts;
            listModel.duration = lisionModel.duration;
            [array addObject:listModel];
        }
        player.allMusicArray = array;//歌曲数组赋值
        [self presentViewController:player animated:YES completion:^{
            
            
        }];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self presentViewController:player animated:YES completion:^{
//                
//                
//            }];
//            
//        });
        
//        HFMusicViewController *player = [HFMusicViewController sharePlayerViewController];
//        HFBaseNavigationController *navc = [[HFBaseNavigationController alloc] initWithRootViewController:player];
//        HFLisionListModel *model = [self.listArray objectAtIndex:indexPath.row];
//        player.song_ID = model.trackID.intValue;      //歌曲的ID
//        player.indexRow = indexPath.row;     //点击的歌曲的下标
        
        //***************** 数组转换 ****************
//        NSMutableArray *array = [NSMutableArray array];
//        for (HFLisionListModel *lisionModel in self.listArray) {
//            HFmusicListModel *listModel = [[HFmusicListModel alloc] init];
//            //        NSLog(@"AAA%@", lisionModel.trackID);
//            listModel.trackId = [NSString stringWithFormat:@"%@", lisionModel.trackID];
//            listModel.title = lisionModel.title;
//            listModel.playtimes = lisionModel.playsCounts;
//            listModel.comments = lisionModel.commentsCounts;
//            listModel.duration = lisionModel.duration;
//            [array addObject:listModel];
//            [listModel release];
//        }
//        player.allMusicArray = array;//歌曲数组赋值
        // ******************************************
        
//        [self.navigationController presentViewController:navc animated:YES completion:^{
//        }];
//        

    }
}


//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
#pragma mark - 很重要
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
